package cn.zy.company.servlet.admin;

import cn.zy.company.entity.User;
import cn.zy.company.service.UserService;
import cn.zy.company.util.Md5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/jsp/admin/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserService userService = new UserService();
        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String s = Md5Util.MD5(password);
            User user1 = userService.find(username, s);
            if (user1 != null) {
                req.getSession().setAttribute("loginUser", user1);
                req.getRequestDispatcher("WEB-INF/jsp/admin/index.jsp").forward(req, resp);
                return;
            }
            resp.sendRedirect("login");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
